package org.cloud.common.util;

import java.security.MessageDigest;
import java.util.UUID;

import org.cloud.common.exception.SlothCloudException;

/**
 * UUID工具类
 * 
 * @author wangyuan
 * @since 2018年9月8日
 */
public class UUIDUtils {

    /**
     * 生成UUID去除-的字符串
     * @return
     */
    public static String generateUUID(){
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replaceAll("-", "");
    }
    
    public static String generateToken() {
        return generateValue(UUID.randomUUID().toString());
    }

    private static final char[] hexCode = "0123456789abcdef".toCharArray();

    public static String toHexString(byte[] data) {
        if(data == null) {
            return null;
        }
        StringBuilder r = new StringBuilder(data.length * 2);
        for ( byte b : data) {
            r.append(hexCode[(b >> 4) & 0xF]);
            r.append(hexCode[(b & 0xF)]);
        }
        return r.toString();
    }

    public static String generateValue(String param) {
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(param.getBytes());
            byte[] messageDigest = algorithm.digest();
            return toHexString(messageDigest);
        } catch (Exception e) {
            throw new SlothCloudException("生成token失败", e);
        }
    }
}
